//
//  ST_SurveyViewController.swift
//  btvideo
//
//  Created by mac on 2019/11/20.
//  Copyright © 2019 JarvanZhang. All rights reserved.
//

import UIKit
import SwifterSwift
import HandyJSON
import SnapKit

class ST_SurveyViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        var root_view_height = model.question_content.height(withConstrainedWidth: 300 - 30, font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular))
        
        if model.input_type != 1{
            root_view_height += 200
        }else{
            
            if  let list = model.item {
                
                var line = list.count/2
                
                if list.count%2 != 0{
                    line += 1
                }
                root_view_height += line.cgFloat * 55 + 55
                
            }else{
                root_view_height += 200
            }
            
        }
        
        
        view.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(iPhoneXSeries ? -70 : -50)
            make.width.equalTo(300)
            make.height.equalTo(root_view_height)
        }
        
        root_view.addSubview(titleLabel)
        root_view.addSubview(content_label)
        
        titleLabel.snp.makeConstraints { (make) in
            make.top.equalToSuperview().offset(25)
            make.centerX.equalToSuperview()
//            make.height.equalTo(UIFont.systemFont(ofSize: 16).lineHeight + 3)
        }
        
        content_label.snp.makeConstraints { (make) in
            make.top.equalTo(titleLabel.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
        }
        
        
        root_view.addSubview(close_btn)
        
        close_btn.snp.makeConstraints { (make) in
            make.width.height.equalTo(22)
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(15)
        }
        
        
        root_view.addSubview(finishBtn)
        
        finishBtn.snp.makeConstraints { (make) in
            make.height.equalTo(36)
            make.width.equalTo(85)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-15)
        }
        
        bind_data()
    }
    
    func bind_data(){
        
        if model.input_type == 1{
            
            guard let list = model.item else {
                return
            }
            
            finishBtn.isHidden = true
            
            let markImage = ST_ImageUtils.imageName("弹幕未选择")!
            
            let selectMarkImage = ST_ImageUtils.imageName("弹幕选择")!
            
            var lastLeftItem:UIButton?
            var lastRightItem:UIButton?
            
            let btnGap = 20.cgFloat
            
            for (idx,item) in list.enumerated(){
                
                let btn = UIButton.init(type: UIButton.ButtonType.custom)
                
                btn.setImageForAllStates(markImage)
                
                btn.setImage(selectMarkImage, for: UIControl.State.selected)
                
                btn.setTitleForAllStates(item.title + "   ")
                btn.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 5, bottom: 0, right: 0)
                btn.titleLabel?.font = UIFont.systemFont(ofSize: 13)
                btn.setTitleColorForAllStates(UIColor.gray)
                
                btn.tag = self.baseTag + idx
                
                root_view.addSubview(btn)
                
                btn.addTarget(self, action: #selector(single_select_click_handle(sender:)), for: UIControl.Event.touchUpInside)
                
                if idx%2 == 0 {
                    
                    btn.snp.makeConstraints { (make) in
                        make.left.equalTo(content_label).offset(25)
                        if let last = lastLeftItem{
                            make.top.equalTo(last.snp.bottom).offset(btnGap)
                        }else{
                            make.top.equalTo(content_label.snp.bottom).offset(btnGap)
                        }
                    }
                    lastLeftItem = btn
                }else{
                    
                    
                    btn.snp.makeConstraints { (make) in
                        
                        make.left.equalTo(content_label).offset(145)
                        
                        if let last = lastRightItem{
                            make.top.equalTo(last.snp.bottom).offset(btnGap)
                        }else{
                            make.top.equalTo(content_label.snp.bottom).offset(btnGap)
                        }
                    }
                    
                    lastRightItem = btn
                }
            }
            
        }else{
            
            finishBtn.isHidden = false
            
            root_view.addSubview(textView)
            textView.snp.makeConstraints { (make) in
                make.left.equalTo(content_label).offset(3)
                make.right.equalTo(content_label).offset(-3)
                make.top.equalTo(content_label.snp.bottom).offset(20)
                make.bottom.equalTo(finishBtn.snp.top).offset(-30)
//                make.height.equalTo(90)
            }
            
            finishBtn.isEnabled = true
        }
        
        
        titleLabel.text = model.question_title
        content_label.text = model.question_content
        
        
        
    }
    

// MARK: - Properties

    var model = ST_SurveyModel()
    
    fileprivate lazy var root_view:UIView = {
       let control = UIView()
        control.backgroundColor = UIColor.white
        control.cornerRadius = 15
        return control
    }()
    
    

    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
//        control.text = ""
        control.textColor = Color.init(hexString: "#333333")
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.regular)
        
        return control
    }()
    

    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#999999")
        control.numberOfLines = 0
//        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var close_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setImageForAllStates(ST_ImageUtils.imageName("surveyClose")!)
        control.addTarget(self, action: #selector(close_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var finishBtn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.cornerRadius = 18
        control.setTitleForAllStates("完成")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        control.setTitleColor(UIColor.white, for: UIControl.State.normal)
        control.setTitleColor(UIColor.init(white: 1, alpha: 0.5), for: UIControl.State.disabled)
        control.isEnabled = false
        control.addTarget(self, action: #selector(finishedHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var textView:UITextView = {
        let control = UITextView.init()
        control.textColor = UIColor.init(hex: 0x333333)
        control.font = UIFont.systemFont(ofSize: 13)
        control.borderColor = Color.init(white: 0, alpha: 0.2)
        control.borderWidth = 1
        control.cornerRadius = 5
        return control
    }()
    
    fileprivate let baseTag = 1048
    fileprivate var lastSelectBtn:UIButton?
    

//    MARK: - Event
    @objc func finishedHandle(){
        
        if model.input_type == 1{
            
            if let selectBtn = lastSelectBtn, let item = model.item?[safe:selectBtn.tag - baseTag]{
                
                let param = ["statistics_id":model.statistics_id,"answer_id":item.id,"answer":item.title] as [String : Any]
                
                JVrequest(PH.answerSurveyApi, parameters: param,success: { (json) in
                    
                    self.close_handle()
                    
                }) { (code, err) in
                    
                    ToastHud(text: err, view: self.view)
                }
                
            }
            
        }else{
            
            if self.textView.text.isEmpty{
                
                ToastHud(text: "输入内容不能为空", view: self.view)
                
                return
            }
            
            let param = ["statistics_id":model.statistics_id,"answer":self.textView.text ?? ""] as [String : Any]
            
            JVrequest(PH.answerSurveyApi, parameters: param,success: { (json) in
                
                self.close_handle()
                
            }) { (code, err) in
                
                ToastHud(text: err, view: self.view)
            }
            
            
        }
        
        
        
        
    }
    
    @objc func single_select_click_handle(sender:UIButton){
        
//        lastSelectBtn?.isSelected = false
//        lastSelectBtn = sender
//        lastSelectBtn?.isSelected = true
//
//        finishBtn.isEnabled = true
        if let item = model.item?[safe:sender.tag - baseTag]{
            
            let param = ["statistics_id":model.statistics_id,"answer_id":item.id,"answer":item.title] as [String : Any]
            
            JVrequest(PH.answerSurveyApi, parameters: param,success: { (json) in
                
                self.close_handle()
                
            }) { (code, err) in
                
                ToastHud(text: err, view: self.view)
            }
            
        }
        
    }
    
    @objc func close_handle(){
        
        goback_previous_controller()
        
    }
    
}

//MARK: - Struct
class ST_SurveyModel : NSObject,HandyJSON {
    
    var statistics_id = 0
    
    var question_title = ""
    
    var question_content = ""
    //  1单选，3输入
    var input_type = 1
    
    var item: [ST_SurveyItemStruct]?
    
    required override init() {
        super.init()
    }
    
}


struct ST_SurveyItemStruct : HandyJSON {
    
    init() {
    }
    
    var id:Int = 0
    var title:String = ""
}
